from typing import List

class Solution:
    def maximizeSquareArea(self, m: int, n: int, hFences: List[int], vFences: List[int]) -> int:
        def getGaps(fences, size):
            fences = sorted([1] + fences + [size])  # sort fence positions and add borders value both at beginning and end
            gaps = [fences[i+1] - fences[i] for i in range(len(fences) - 1)]  # continuous fence gap widths

            combinations = set()
            for i in range(len(gaps)):  # traverse the gaps starting from each and calculating all possible gap groups
                sum_ = 0
                for j in range(i, len(gaps)):  # traverse gaps combinations from the start and step by step sums up the widths
                    sum_ += gaps[j]
                    combinations.add(sum_)  # add cumulative sum into res to simulate all contiguous tracks

            return combinations

        hGaps = getGaps(hFences, m)
        vGaps = getGaps(vFences, n)

        max_area = 0
        for gap in hGaps:
            if gap in vGaps:
                max_area = max(max_area, gap  ** 2)  # 计算面积

        return max_area if max_area > 0 else -1

        max_area = 0
        for gap in hGaps:
            if gap in vGaps:
                max_area = max(max_area, gap  ** 2)  # 计算面积

        return max_area if max_area > 0 else -1


print(Solution().maximizeSquareArea(3,9,[2],[8,6,5,4]))
